import { CozeAPI, RoleType, ChatEventType } from '@coze/api';

const COZE_API_TOKEN = import.meta.env.VITE_COZE_API_TOKEN;
const COZE_BOT_ID = import.meta.env.VITE_COZE_BOT_ID;

console.log('Raw VITE_COZE_BOT_ID from import.meta.env:', import.meta.env.VITE_COZE_BOT_ID);
console.log('COZE_BOT_ID from env:', COZE_BOT_ID);

if (!COZE_API_TOKEN || !COZE_BOT_ID) {
  console.error('Coze API Token or Bot ID is not set in environment variables.');
}

const client = new CozeAPI({
  token: COZE_API_TOKEN,
  baseURL: 'https://api.coze.cn',
  allowPersonalAccessTokenInBrowser: true, // 添加这行
});

export async function sendMessageToCoze(
  userId: string,
  message: string,
  conversationId?: string
): Promise<string> {
  if (!COZE_API_TOKEN || !COZE_BOT_ID) {
    return 'Error: Coze API Token or Bot ID is not configured.';
  }

  try {
    const stream = await client.chat.stream({
      bot_id: String(COZE_BOT_ID), // 确保 bot_id 是字符串类型
      user_id: userId,
      additional_messages: [{ role: RoleType.User, content: message, content_type: 'text' }],
      conversation_id: conversationId,
    });

    let fullResponse = '';
    for await (const part of stream) {
      console.log('Coze Stream Part:', part); // 添加这行日志
      if (part.event === ChatEventType.CONVERSATION_MESSAGE_DELTA) {
        fullResponse += part.data.content;
      }
      // You can handle other events like CONVERSATION_CHAT_COMPLETED, etc. here if needed
    }
    console.log('Coze Final Response:', fullResponse); // 添加这行日志
    return fullResponse;
  } catch (error) {
    console.error('Error sending message to Coze:', error);
    return 'Error communicating with Coze AI.';
  }
}